import React, { useEffect } from 'react';
import { connect } from 'dva';
import { Form, FormItem, createFormActions, FormEffectHooks } from '@formily/antd';
import { Input, Switch } from '@formily/antd-components';
import classNames from 'classnames';
import throttle from 'lodash/throttle';
import omit from 'lodash/omit';
import has from 'lodash/has';
import get from 'lodash/get';
import styles from '../../styles.less';

const actions = createFormActions();

const { onFormInputChange$ } = FormEffectHooks;

function ForAsync({ dispatch, current }) {
  useEffect(() => {
    // 清空状态
    actions.reset({ validate: false });

    // 剔除holder是冗余的key
    const keys = Object.keys(actions.getFormGraph()).filter(val => val !== '');

    // 遍历，给所有的formItem设置值
    keys.forEach(value => {
      if (has(current, value)) {
        actions.setFieldValue([value], get(current, value));
      }
    });
  }, [current]);

  return (
    <Form
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={() => {
        // 只监控人工操作引起的FormItem值变化
        onFormInputChange$().subscribe(
          throttle(
            async () => {
              await actions.validate({ silent: true });
              // actions.getFormState().valid取到的结果是异步的，所以必须用到await actions.validate才能得到精确的结果
              const isValid = actions.getFormState().valid;

              // 校验失败
              if (!isValid) {
                return;
              }

              // 当前面板所有formitem字段的值
              let formValues = actions.getFormState().values;

              // 必填, 补充whitespace等字段
              if (get(formValues, 'rules.requiredRule.required') === true) {
                formValues = {
                  ...formValues,
                  rules: {
                    ...formValues.rules,
                    requiredRule: { required: true, whitespace: true, message: '必填项' },
                  },
                };
              }

              // required==false时剔除，（因为在reset()时 required会变成false）
              if (get(formValues, 'rules.requiredRule.required') === false) {
                formValues = {
                  ...formValues,
                  rules: omit(formValues.rules, ['requiredRule']),
                };
              }

              dispatch({
                type: 'formDesigner/updateNode',
                payload: formValues,
              });
            },
            300,
            { trailing: true, leading: false }
          )
        );
      }}
    >
      <FormItem
        label="组件路径"
        name="path"
        allowClear
        required
        triggerType="onChange"
        disabled
        component={Input}
        placeholder="无"
      />

      <FormItem
        label="显示"
        name="display"
        triggerType="onChange"
        component={Switch}
        initialValue
      />
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  current: formDesigner.current,
}))(ForAsync);
